package cn.haoxsf.app.common.apo.exception;


import cn.haoxsf.app.common.api.CommonResult;
import cn.haoxsf.app.common.api.enums.SystemExceptionEnum;
import cn.haoxsf.app.common.exception.BaseException;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @program: rest
 * @description: 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 * @author: Ele qvbanfm@qq.com
 * @create: 2019-10-06 14:56
 **/
@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {
    /**
     * 业务异常统一处理
     *
     * @param xe
     * @return
     */
    @ExceptionHandler(BaseException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CommonResult notFount(BaseException xe) {
        return CommonResult.error(xe.getCode(), xe.getMsg());
    }
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public CommonResult RuntimeException(RuntimeException xe) {
        log.error("运行异常[{}]",xe.getLocalizedMessage());
        return CommonResult.error(505,"服务器异常！");
    }

    /**
     * HttpMessageNotReadableException
     * JSON对象参数不正确
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public CommonResult handleMessageNotReadableException(HttpMessageNotReadableException e) {
        return CommonResult.error(SystemExceptionEnum.HTTP_MESSAGE_NOT_READABLE_EXCEPTION);
    }
}
